﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using ChoViet.Model;
using ChoViet.Lib.Common;
using ChoViet.Admin.Properties;
using ChoViet.Admin.ViewModels;
using ChoViet.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using ChoViet.Lib.Helpers;
using ChoViet.Systems;

namespace ChoViet.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen.
    /// Date: 20/08/2011.
    /// </summary>
    [RoleHelper(Roles = RoleSystem.Mail)]
    public class MailCategoryController : Controller
    {
        //
        // GET: /MailCategory/
        ChoVietDataContext eDataContext = new ChoVietDataContext();

        public ActionResult Index(int? page)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Mail))
                {
                    if (!page.HasValue)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("articleCategory.order", "order", "id").ToString();
                    string orderDir = UserState.getUserStateFromRequest("articleCategory.orderDir", "orderDir", "desc").ToString();
                    string keyword = UserState.getUserStateFromRequest("articleCategory.Keyword", "Keyword", "").ToString();
                    keyword = keyword.Trim();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("articleCategory.pageSize", "PageSize", 20).ToString());
                    string strPub = UserState.getUserStateFromRequest("articleCategory.CurrentPubStatus", "CurrentPubStatus", "").ToString();

                    int? CurrentPubStatus = null;
                    if (!string.IsNullOrEmpty(strPub))
                        CurrentPubStatus = Convert.ToInt32(strPub);


                    var categories = eDataContext.MailCategories
                        .Where(c => CurrentPubStatus.HasValue ? c.PubYN == (CurrentPubStatus.HasValue && CurrentPubStatus.Value == 1 ? true : false) : true)
                        .Where(c => (string.IsNullOrEmpty(keyword) ? true : c.Name.ToLower().Contains(keyword.ToLower().Trim())
                        ))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    //var categories = eDataContext.ArticleCategories.OrderBy(string.Format("{0} {1}", order, orderDir)).ToList();

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new MailCategoryViewModel
                    {
                        MailCategories = categories,
                        CurrentPubStatus = CurrentPubStatus,
                        Keyword = keyword
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /MailCategory/Details/5

        public ActionResult Details(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Mail))
                {
                    //List<MailCategory> listParent = eDataContext.MailCategories.Where(c => c.ParentID == null).ToList();
                    MailCategory cat = eDataContext.MailCategories.Where(ca => ca.ID == id).FirstOrDefault();

                    return View(new MailCategoryInputModel
                    {
                        //Categories = listParent,
                        Category = cat
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /MailCategory/Create

        public ActionResult Create()
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Mail))
                {
                    List<MailCategory> listParent = eDataContext.MailCategories.Where(c => c.ParentID == null).ToList();
                    MailCategory cat = new MailCategory();
                    return View(new MailCategoryInputModel
                    {
                        Categories = listParent,
                        Category = cat
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        } 

        //
        // POST: /MailCategory/Create

        [HttpPost]
        public ActionResult Create(MailCategoryInputModel m)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Mail))
                {
                    UpdateModel(m);

                    m.Category.AddDate = DateTime.Now;
                    m.Category.AddBy = UserManager.GetUserId();

                    eDataContext.MailCategories.InsertOnSubmit(m.Category);
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /MailCategory/Edit/5
 
        public ActionResult Edit(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Mail))
                {
                    List<MailCategory> listParent = eDataContext.MailCategories.Where(c => c.ParentID == null).ToList();
                    MailCategory cat = eDataContext.MailCategories.Where(ca => ca.ID == id).FirstOrDefault();

                    return View(new MailCategoryInputModel
                    {
                        Categories = listParent,
                        Category = cat
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /MailCategory/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, MailCategoryInputModel m)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Mail))
                {
                    m.Category = eDataContext.MailCategories.Where(mc => mc.ID == id).FirstOrDefault();
                    UpdateModel(m);

                    m.Category.ModifyDate = DateTime.Now;
                    m.Category.ModifyBy = UserManager.GetUserId();

                    eDataContext.SubmitChanges();
                    
                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /MailCategory/Delete/5

        public ActionResult Delete(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Mail))
                {
                    MailCategory mc = eDataContext.MailCategories.Where(mca => mca.ID == id).FirstOrDefault();
                    int nItem = eDataContext.MailCategories.Where(m => m.ParentID.HasValue && m.ParentID.Value == id).Count();
                    if (nItem > 0)
                        throw new Exception("Chuyên mục cha không thể xoá được. Hãy xoá chuyên mục con trước.");
                    return View(mc);
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /MailCategory/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Mail))
                {
                    MailCategory mc = eDataContext.MailCategories.Where(mca => mca.ID == id).FirstOrDefault();
                    eDataContext.MailCategories.DeleteOnSubmit(mc);
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
